
package com.example.origin.demo.demo.currentprint;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class AlteratePrint2 {
    static Thread threadA = null;
    static Thread threadB = null;


    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        Condition conditionA = lock.newCondition();
        Condition conditionB = lock.newCondition();

        threadA = new Thread(() -> {
            lock.lock();
            try {
                for (int i = 0; i < 100; i++) {
                    if (i % 2 == 0) {
                        System.out.print(i + " ");

                        try {
                            conditionA.await();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                        conditionB.signal();

                    }
                }
            } finally {
                lock.unlock();
            }
        });
        threadB = new Thread(() -> {
            lock.lock();
            try {
                for (int i = 0; i < 100; i++) {
                    if (i % 2 == 1) {
                        System.out.print(i + " ");
                        conditionA.signal();

                        try {
                            conditionB.await();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            } finally {
                lock.unlock();
            }
        });

        threadA.start();
        threadB.start();


    }
}